package com.example.springbootminiodemo.util;

import com.example.springbootminiodemo.api.Result;
import com.example.springbootminiodemo.entity.ImageUri;
import io.minio.MinioClient;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import net.coobird.thumbnailator.Thumbnails;
import javax.crypto.KeyGenerator;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: LL
 * @Date: 2020/3/30 11:32
 */
@Slf4j
@PropertySource("classpath:application.properties")
@Component
public class MinIOUtils {
    @Value("${minio.endPoint}")
    private String  endPoint;
    @Value("${minio.port}")
    private Integer  port;
    @Value("${minio.accessKey}")
    private String accessKey;
    @Value("${minio.secretKey}")
    private String secretKey;

    @Value("${minio.bucketName}")
    private String  bucketName;
    private static MinioClient instance ;
    public MinioClient getInstance() throws InvalidPortException, InvalidEndpointException {
        if (instance == null) {
            instance = new MinioClient(endPoint,port,accessKey,secretKey);
        }
        return instance;
    }

    /**
     * 下载图片
     * @param uri
     * @return
     * @throws Exception
     */
    public String  getImageByUri(String uri) throws Exception  {
        // 返回一个下载地址
        return getInstance().presignedGetObject(bucketName,uri);
    }

    /**
     * 上传图片
     * @param multipartFile
     * @return
     */
    public Result<?> uploadImage(MultipartFile multipartFile){
        String fileName=multipartFile.getOriginalFilename();
        ImageUri imageUri=new ImageUri();
        String fileCode= UUIDGenerator.generate()+fileName.substring(fileName.lastIndexOf('.'));
        try {
            InputStream inputStream=multipartFile.getInputStream();
            //如果大于500kb,则进行压缩
            if (multipartFile.getSize()>1024*500){
                File tempFIe= File.createTempFile("temp",fileName.substring(fileName.lastIndexOf('.')));
                Thumbnails.of(inputStream).scale(0.25f).toFile(tempFIe);
                FileInputStream fileInputStream=new FileInputStream(tempFIe);
                Long l= Long.valueOf(fileInputStream.available());
                log.info("Size:"+String.valueOf(l));
                getInstance().putObject(bucketName,fileCode,fileInputStream,l,"application/octet-stream");
                fileInputStream.close();

            }else {
                Long l= Long.valueOf(inputStream.available());
                getInstance().putObject(bucketName,fileCode,inputStream,l,"application/octet-stream");
            }

        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            return Result.error("保存失败");
        }
        imageUri.setImageUri(fileCode);
        return Result.ok(imageUri);
    }

    /**
     * 批量下载图片
     * @param strings
     * @return
     * @throws Exception
     */
    public List<ImageUri> getUriList(List<String> strings) throws Exception {

        List<ImageUri> list=new ArrayList<>();
        ImageUri uri;
        for (String s:strings){
            uri=new ImageUri();
            uri.setImageUri(getInstance().presignedGetObject(bucketName,s));
            list.add(uri);
        }

        return list;
    }
}
